import { v4 } from 'uuid';

export function dataURLtoBlob(base64Buf: string): Blob {
  const arr = base64Buf.split(',');
  const typeItem = arr[0];
  const mime = typeItem.match(/:(.*?);/)![1];
  const bstr = window.atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

export function dataURLtoFile(base64Buf: string): Blob {
  const arr = base64Buf.split(',');
  const typeItem = arr[0];
  const mime = typeItem.match(/:(.*?);/)![1];
  const bstr = window.atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], v4(), { type: mime });
}

export function urlToBase64(url: string, mineType?: string): Promise<string> {
  return new Promise((resolve, reject) => {
    let canvas = document.createElement('canvas') as HTMLCanvasElement | null;
    const ctx = canvas!.getContext('2d');

    const img = new Image();
    img.crossOrigin = '';
    img.onload = function () {
      if (!canvas || !ctx) {
        return reject('');
      }
      canvas.height = img.height;
      canvas.width = img.width;
      ctx.drawImage(img, 0, 0);
      const dataURL = canvas.toDataURL(mineType || 'image/png');
      canvas = null;
      resolve(dataURL);
    };
    img.onerror = function (err) {
      console.error('图片加载失败：', err);
      reject('');
    };

    img.src = url;
  });
}

export function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = (e: ProgressEvent<FileReader>) => {
      if (e.target) {
        const result = e.target?.result as string;
        resolve(result);
      } else {
        reject('');
      }
    };
    fileReader.onerror = (err) => {
      reject(err);
    };
  });
}

export function loadingUrl(url: string): Promise<boolean> {
  return new Promise((resolve, reject) => {
    try {
      const image = new Image();
      image.src = url;
      image.onload = () => {
        resolve(true);
      };
      image.onerror = () => {
        resolve(false);
      };
    } catch (err) {
      reject(err);
    }
  });
}
